package com.customization.test.demo.util;

import com.weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.*;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.hrm.User;
import weaver.integration.entrance.utils.StringUtils;
import weaver.system.SystemComInfo;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 图片文件相关工具类
 * Created by YeShengtao on 2020/9/24 15:19
 */
public class ImageFileUtils {

    private static final BaseBean  baseBean = new BaseBean();

    private static final ImageFileIdUpdate imageFileIdUpdate = new ImageFileIdUpdate();


    public static ImageFileManager imageFileManager(String docid) {
        RecordSet recordSet = new RecordSet();
        String sql1 = "select imagefileid from DocImageFile where docid = "+docid+" order by versionid desc ";
        recordSet.execute(sql1);
        String imagefileid = null;
        if (recordSet.next()){
            imagefileid = recordSet.getString("imagefileid");
        }
        String sql2 = "select imagefileid, filerealpath, fileSize, imagefilename from ImageFile "+
                "where imagefileid = "+imagefileid;
        recordSet.execute(sql2);
        Map<String,String> sqlData = new HashMap<>();
        if (recordSet.next()){
            sqlData.put("imagefileid",recordSet.getString("imagefileid"));
            sqlData.put("filerealpath",recordSet.getString("filerealpath"));
            sqlData.put("fileSize",recordSet.getString("fileSize"));
            sqlData.put("imagefilename",recordSet.getString("imagefilename"));
        }
        if (sqlData.size() == 0) {
            return null;
        }
        if (StringUtils.isEmpty(imagefileid)) {
            return null;
        }
        ImageFileManager imageFileManager = new ImageFileManager();
        imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid));
        return imageFileManager;
    }


    //--------------------分隔线--------------------

    /**
     * 上传文件
     * 文件存入到ecology的系统中
     * @param doc 文件流
     * @param user 当前操作用户
     * @param docCategory 文档目录id
     * @param filename 文件名
     * @return docId
     */
    public static int uploadFile(InputStream doc, User user, String docCategory, String filename) throws Exception {
        int docid = -1;
        int mainId = 0;
        int subId = 0;
        int secId = 0;
        secId = Integer.parseInt(docCategory);
        int imgid = SaveFile(doc, filename);
        baseBean.writeLog("imgid:" + imgid);
        if (imgid > 0) {
            SecCategoryComInfo scc = new SecCategoryComInfo();
            DocComInfo dc = new DocComInfo();
            DocManager dm = new DocManager();
            DocViewer dv = new DocViewer();
            DocImageManager imgManger = new DocImageManager();
            // get doc id
            RecordSet rs1 = new RecordSet();
            docid = dm.getNextDocId(rs1);
            String ext = getFileExt(filename);
            imgManger.resetParameter();
            imgManger.setImagefilename(filename);
            if (ext.equalsIgnoreCase("doc")) {
                imgManger.setDocfiletype("3");
            } else if (ext.equalsIgnoreCase("xls")) {
                imgManger.setDocfiletype("4");
            } else if (ext.equalsIgnoreCase("ppt")) {
                imgManger.setDocfiletype("5");
            } else if (ext.equalsIgnoreCase("wps")) {
                imgManger.setDocfiletype("6");
            } else if (ext.equalsIgnoreCase("docx")) {
                imgManger.setDocfiletype("7");
            } else if (ext.equalsIgnoreCase("xlsx")) {
                imgManger.setDocfiletype("8");
            } else if (ext.equalsIgnoreCase("pptx")) {
                imgManger.setDocfiletype("9");
            } else if (ext.equalsIgnoreCase("et")) {
                imgManger.setDocfiletype("10");
            } else {
                imgManger.setDocfiletype("2");
            }
            imgManger.setDocid(docid);
            imgManger.setImagefileid(imgid);
            imgManger.setIsextfile("1");
            imgManger.AddDocImageInfo();

            String now = "";
            String date = "";
            String time = "";
            now = TimeUtil.getCurrentTimeString();
            int pos = now.indexOf(" ");
            if (pos != -1) {
                date = now.substring(0, pos);
                time = now.substring(pos + 1, now.length());
            }
            dm.setId(docid);
            dm.setSeccategory(secId);
            dm.setLanguageid(user.getLanguage());
            dm.setDoccontent("");
            dm.setDocstatus("1");
            dm.setDocsubject(getFileMainName(filename));
            dm.setDoccreaterid(user.getUID());
            dm.setUsertype(user.getLogintype());
            dm.setOwnerid(user.getUID());
            dm.setDoclastmoduserid(user.getUID());
            dm.setDoccreatedate(date);
            dm.setDoclastmoddate(date);
            dm.setDoccreatetime(time);
            dm.setDoclastmodtime(time);
            dm.setDoclangurage(user.getLanguage());
            dm.setKeyword(getFileMainName(filename));
            dm.setIsapprover("0");
            dm.setIsreply("");
            dm.setDocdepartmentid(user.getUserDepartment());
            dm.setDocreplyable("1");
            dm.setAccessorycount(1);
            dm.setParentids("" + docid);
            dm.setOrderable("" + scc.getSecOrderable(secId));
            dm.setClientAddress("内部");
            dm.setUserid(user.getUID());
            dm.AddDocInfo();
            //set share
            dm.AddShareInfo();
            dc.addDocInfoCache("" + docid);
            dv.setDocShareByDoc("" + docid);
        }
        return docid;
    }

    /**
     * 保存文件
     *
     * @param fis
     * @param filename
     * @return
     */
    private static int SaveFile(InputStream fis, String filename)  {
        int imgid = 0;
        boolean needzip = false;
        boolean needzipencrypt = false;
        boolean flagbool = false;
        SystemComInfo syscominfo = new SystemComInfo();
        if ("1".equals((syscominfo.getNeedzip()))) needzip = true;
        String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());
        File parentdir = new File(createdir);
        if (!parentdir.exists()) parentdir.mkdirs();
        String newfilename = weaver.general.Util.getRandom();
        if (needzip) newfilename += ".zip";
        File newfile = new File(createdir, newfilename);
        while (newfile.exists()) {
            newfilename = weaver.general.Util.getRandom();
            if (needzip) newfilename += ".zip";
            newfile = new File(createdir, newfilename);
        }
        //保存附件
        byte[] buffer = new byte[64 * 1024];
        long filesize = 0;
        int buf = -1;
        String contenttype = "text/plain";
        ZipOutputStream zos = null;
        BufferedOutputStream zos2 = null;
        try {
            if (needzip) {
                zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newfile)));
                zos.setMethod(ZipOutputStream.DEFLATED);
                zos.putNextEntry(new ZipEntry(getFileMainName(newfilename)));
                while ((buf = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, buf);
                    filesize += buf;
                }
                zos.flush();
                zos.close();
            } else {
                zos2 = new BufferedOutputStream(new FileOutputStream(newfile));
                while ((buf = fis.read(buffer)) != -1) {
                    zos2.write(buffer, 0, buf);
                    filesize += buf;
                }
                zos2.flush();
                zos2.close();
            }
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            if (zos != null) {
                try {
                    zos.flush();
                    zos.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
            if (zos2 != null) {
                try {
                    zos2.flush();
                    zos2.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.getStackTrace();
            }
        }

        RecordSet rs2 = new RecordSet();
        char separator = weaver.general.Util.getSeparator();
        String imagefileused = "1";
        String iszip = "0";
        String isencrypt = "0";
        if (needzip) iszip = "1";
        if (needzipencrypt) isencrypt = "1";
        //生成附件文件id
        imgid = imageFileIdUpdate.getImageFileNewId();

        String para = "" + imgid + separator + filename + separator + contenttype + separator
                + imagefileused + separator + (createdir + newfilename) + separator
                + iszip + separator + isencrypt + separator + filesize;

        flagbool = rs2.executeProc("ImageFile_Insert", para);
        if (!flagbool) {
            return 0;
        }
        return imgid;
    }

    private static String getFileMainName(String fileName) {
        if (fileName == null) return "";
        int pos = fileName.indexOf(".");
        if (pos != -1) {
            fileName = fileName.substring(0, pos);
        }
        return fileName;
    }

    private static String getFileExt(String file) {
        if (file == null || "".equals(file.trim())) {
            return "";
        } else {
            int idx = file.lastIndexOf(".");
            if (idx == -1) {
                return "";
            } else {
                if (idx + 1 >= file.length()) {
                    return "";
                } else {
                    return file.substring(idx + 1);
                }
            }
        }
    }

}
